//
//  AppDelegate.swift
//  竖屏状态弹出横屏的控制器
//
//  Created by BlueDancer on 2019/8/15.
//  Copyright © 2019 SanJiang. All rights reserved.
//

import UIKit

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
    
    var window: UIWindow?
    
    func application(_ application: UIApplication, supportedInterfaceOrientationsFor window: UIWindow?) -> UIInterfaceOrientationMask {
        return .all
    }
}

class PortraitViewController: UIViewController {
    
    override var shouldAutorotate: Bool {
        return false
    }
    
    override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
        return .portrait
    }
    
    @IBAction func present(_ sender: Any) {
        self.present(UINavigationController(rootViewController: LandscapeViewController()), animated: true, completion: nil)
    }
}

class LandscapeViewController : UIViewController {
    
    override var shouldAutorotate: Bool {
        return true
    }
    
    override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
        return .landscape
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = .red
        
        let label = UILabel.init()
        label.text = "Test"
        label.backgroundColor = .green
        view.addSubview(label)
        label.translatesAutoresizingMaskIntoConstraints = false
        label.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
        label.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
    }
    
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        dismiss(animated: true, completion: nil)
    }
}

extension UINavigationController {
    open override var shouldAutorotate: Bool {
        return self.topViewController?.shouldAutorotate ?? false
    }
    
    open override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
        return self.topViewController?.supportedInterfaceOrientations ?? .portrait
    }
}

extension UITabBarController {
    var sj_topViewController: UIViewController? {
        return self.selectedIndex != NSNotFound ? self.selectedViewController : self.viewControllers?.first
    }
    
    open override var shouldAutorotate: Bool {
        return self.sj_topViewController?.shouldAutorotate ?? false
    }
    
    open override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
        return self.sj_topViewController?.supportedInterfaceOrientations ?? .portrait
    }
}
